package com.lhh.springcommon.interceptor;

import com.google.common.net.HttpHeaders;
import com.lhh.springcommon.exception.CustomException;
import com.lhh.springcommon.utils.CodeEnum;
import com.lhh.springcommon.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt拦截
 * @author 李厚航
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Integer> userIdThreadLocal = new ThreadLocal<>();

    private final JwtUtil jwtUtil;

    @Autowired
    public JwtInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //token不存在
        if(token == null || "".equals(token)){
            throw new CustomException(CodeEnum.HEADER_NOT_TOKEN);
        }
        //验证token
        Jws<Claims> claimsBody = jwtUtil.getClaimsBody(token);
        Integer userId = (Integer) claimsBody.getPayload().get("userId");
        userIdThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userIdThreadLocal.remove();
    }

    public static Integer getUserIdFromThreadLocal() {
        return userIdThreadLocal.get();
    }
}
